<?php

class Connection
{
    protected $conn;

    protected $read_buffer = '';

    protected $write_buffer = '';

    public function __construct($conn)
    {
        $this->conn = $conn;
    }

    public function handle()
    {
        Reactor::getInstance()->add($this->conn, Reactor::READ, \Closure::fromCallable([$this, 'read']));
    }

    private function read($conn)
    {
        $this->read_buffer = '';
        if (is_resource($conn)) {
            while ($content = fread($conn, 65535)) {
                $this->read_buffer .= $content;
            }
        }

        if ($this->read_buffer) {
            Reactor::getInstance()->add($conn, Reactor::WRITE, \Closure::fromCallable([$this, 'write']));
        } else {
            Reactor::getInstance()->del($conn);
            fclose($conn);
        }
    }

    private function write($conn)
    {
        if (is_resource($conn)) {
            fwrite($conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html;charset=utf8\r\nContent-Length:11\r\nConnection: keep-alive\r\n\r\nHello!world");
        }
    }

}